import { ref } from 'vue'
import { defineStore } from 'pinia'
import {
  getCityData,
  getAdcodeData,
  getWeatherData,
  getFutureWeatherData,
} from '@/utils/index'

export const useWeatherStore = defineStore('weather', () => {
  const cityData = ref()
  const weatherData = ref()
  const adcodeData = ref()
  const futureWeatherData = ref([])
  const error = ref(null)

  const fetchCityData = async () => {
    try {
      const res = await getCityData()
      cityData.value = res
    } catch (err) {
      error.value = '城市信息获取失败'
      console.error(err)
    }
  }
  const fetchAdcodeData = async (address) => {
    try {
      const adcode = await getAdcodeData(address)
      adcodeData.value = adcode.geocodes?.[0]?.adcode
    } catch (err) {
      error.value = '地址信息获取失败'
      console.error(err)
    }
  }
  const fetchWeatherData = async (adcode) => {
    try {
      const wea = await getWeatherData(adcode)
      weatherData.value = wea.lives?.[0]
    } catch (err) {
      error.value = '城市天气信息获取失败'
      console.erro(err)
    }
  }
  const fetchFutureWeatherData = async (adcode) => {
    try {
      const future = await getFutureWeatherData(adcode)
      futureWeatherData.value = future.forecasts?.[0]?.casts?.slice(0, 4)
    } catch (err) {
      error.value = '城市预报天气信息获取失败'
      console.erro(err)
    }
  }

  return {
    cityData,
    adcodeData,
    weatherData,
    futureWeatherData,
    fetchCityData,
    fetchAdcodeData,
    fetchWeatherData,
    fetchFutureWeatherData,
    error,
  }
})
